import { fetchAllMaintenanceRecords, deleteMaintenanceRecord,fetchMaintenanceRecords,createMaintenance, completeMaintenanceRecord } from '@/api/maintenance';

const state = {
  loading: false,
  error: null,
  maintenanceRecords: [],
  allMaintenanceRecords: [], // 新增属性用于存储所有维修记录
  inventory: {}
};

const mutations = {
  SET_LOADING(state, status) {
    state.loading = status;
  },
  SET_ERROR(state, error) {
    state.error = error;
  },
  SET_MAINTENANCE_RECORDS(state, records) {
    state.maintenanceRecords = records;
  },
  SET_ALL_MAINTENANCE_RECORDS(state, records) { // 新增mutation
    state.allMaintenanceRecords = records;
  },
  UPDATE_MAINTENANCE_STATUS(state, payload) {
    const record = state.maintenanceRecords.find(r => r.id === payload.id);
    if (record) {
      record.status = payload.status;
    }
  },
  SET_INVENTORY(state, inventory) {
    state.inventory = inventory;
  },
  DELETE_MAINTENANCE_RECORD(state, id) {
    state.allMaintenanceRecords = state.allMaintenanceRecords.filter(record => record.id !== id);
    state.maintenanceRecords = state.maintenanceRecords.filter(record => record.id !== id);
  },
};

const actions = {
  fetchMaintenanceRecords({ commit }, materialId) {
    return new Promise((resolve, reject) => {
      commit('SET_LOADING', true);
      commit('SET_ERROR', null);

      fetchMaintenanceRecords(materialId)
        .then(response => {
          commit('SET_MAINTENANCE_RECORDS', response.data);
          resolve(response);
        })
        .catch(error => {
          commit('SET_ERROR', '加载维护记录失败，请稍后再试！');
          reject(error);
        })
        .finally(() => {
          commit('SET_LOADING', false);
        });
    });
  },
  fetchAllMaintenanceRecords({ commit }) { // 新增action
    return new Promise((resolve, reject) => {
      commit('SET_LOADING', true);
      commit('SET_ERROR', null);

      fetchAllMaintenanceRecords()
        .then(response => {
          commit('SET_ALL_MAINTENANCE_RECORDS', response.data);
          resolve(response);
        })
        .catch(error => {
          commit('SET_ERROR', '加载全部维护记录失败，请稍后再试！');
          reject(error);
        })
        .finally(() => {
          commit('SET_LOADING', false);
        });
    });
  },
  async createMaintenance({ commit }, maintenanceForm) {
    return new Promise(async (resolve, reject) => {
      try {
        commit('SET_LOADING', true);
        commit('SET_ERROR', null);
        await createMaintenance(maintenanceForm);
        resolve();
      } catch (error) {
        commit('SET_ERROR', '提交维护信息失败，请稍后再试！');
        reject(error);
      } finally {
        commit('SET_LOADING', false);
      }
    });
  },
  async completeMaintenance({ commit }, record) {
    try {
      // 调用后端API完成维修记录并更新库存
      await completeMaintenanceRecord(record);

      // 更新本地状态中的维修记录状态
      commit('UPDATE_MAINTENANCE_STATUS', { id: record.id, status: '已完成' });

      return true;
    } catch (error) {
      console.error('Failed to complete maintenance:', error.message);
      throw new Error(`完成维修失败: ${error.message}`);
    }
  },

  async deleteMaintenanceRecord({ commit }, id) {
    try {
      await deleteMaintenanceRecord(id);
      commit('DELETE_MAINTENANCE_RECORD', id);
      return true;
    } catch (error) {
      console.error('Failed to delete maintenance record:', error.message);
      throw new Error('无法删除维修记录');
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};